import React, { useState, useEffect } from 'react';
import './CreateMaterial.css';

const CreateMaterial = () => {
  const [name, setName] = useState('');
  const [spec, setSpec] = useState('');
  const [unit, setUnit] = useState('');
  const [pricePerUnit, setPricePerUnit] = useState(0);
  const [materialSpecItems, setMaterialSpecItems] = useState([]);

  useEffect(() => {
    const fetchMaterialSpecItems = async () => {
      try {
        const response = await fetch('/alldata');
        const data = await response.json();
        setMaterialSpecItems(data.material_spec_items);
      } catch (error) {
        console.error('Error fetching material spec items:', error);
      }
    };
    fetchMaterialSpecItems();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await fetch('/create/material', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `name=${name}&spec=${spec}&unit=${unit}&price_per_unit=${pricePerUnit}`,
      });
      const data = await response.json();
      console.log(data);
      // 重新获取物料信息
      const newResponse = await fetch('/alldata');
      const newData = await newResponse.json();
      setMaterialSpecItems(newData.material_spec_items);
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const handleDelete = async (itemId) => {
    try {
      const response = await fetch(`/delete/${itemId}`);
      const data = await response.json();
      console.log(data);
      // 重新获取物料信息
      const newResponse = await fetch('/alldata');
      const newData = await newResponse.json();
      setMaterialSpecItems(newData.material_spec_items);
    } catch (error) {
      console.error('Error deleting item:', error);
    }
  };

  return (
    <div className="create-material-container">
      <h1>物料信息创建</h1>
      <form className="create-material-form" onSubmit={handleSubmit}>
        <label>
          名称:
          <input type="text" value={name} onChange={(e) => setName(e.target.value)} required />
        </label>
        <label>
          规格:
          <input type="text" value={spec} onChange={(e) => setSpec(e.target.value)} required />
        </label>
        <label>
          单位:
          <input type="text" value={unit} onChange={(e) => setUnit(e.target.value)} required />
        </label>
        <label>
          单价:
          <input type="number" step="0.01" value={pricePerUnit} onChange={(e) => setPricePerUnit(e.target.value)} required />
        </label>
        <button type="submit">创建</button>
      </form>
      <h1>Material Spec</h1>
      <table className="create-material-table">
        <thead>
          <tr>
            <th>物料ID</th>
            <th>名称</th>
            <th>规格</th>
            <th>单位</th>
            <th>单价</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {materialSpecItems.map((item) => (
            <tr key={item.item_id}>
              <td>{item.item_id}</td>
              <td>{item.name}</td>
              <td>{item.spec}</td>
              <td>{item.unit}</td>
              <td>{item.price_per_unit}</td>
              <td>
                <a href={`/edit/material/${item.item_id}`}>Edit</a>
                <button onClick={() => handleDelete(item.item_id)}>Delete</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default CreateMaterial;
